package com.heima.wemedia.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.heima.file.service.FileStorageService;
import com.heima.model.common.dtos.PageResponseResult;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.wemedia.dto.WmMaterialDto;
import com.heima.model.wemedia.pojos.WmMaterial;
import com.heima.model.wemedia.pojos.WmNewsMaterial;
import com.heima.model.wemedia.pojos.WmUser;
import com.heima.utils.thread.WmTheadLocalUtil;
import com.heima.wemedia.mapper.WmNewsMaterialMapper;
import com.heima.wemedia.service.WmMaterialService;
import com.heima.wemedia.mapper.WmMaterialMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import java.io.IOException;
import java.util.Date;
import java.util.UUID;

/**
 * @author 石头
 * @description 针对表【wm_material(自媒体图文素材信息表)】的数据库操作Service实现
 * @createDate 2022-06-14 00:25:50
 */
@Service
@Slf4j
public class WmMaterialServiceImpl extends ServiceImpl<WmMaterialMapper, WmMaterial>
        implements WmMaterialService {

    @Resource
    private FileStorageService fileStorageService;

    @Resource
    private WmNewsMaterialMapper wmNewsMaterialMapper;

    /**
     * 素材图片上传
     *
     * @param multipartFile
     * @return
     */
    public ResponseResult uploadPicture(MultipartFile multipartFile) {


        // img 原来名称
        String originalFilename = multipartFile.getOriginalFilename();
        // new 新名称
        String uuid = UUID.randomUUID().toString().replace("-", "");
        String newFileName = uuid + originalFilename.substring(originalFilename.indexOf("."));
        String filePath = null;
        try { // 上传图片
            filePath = fileStorageService.uploadImgFile("", newFileName, multipartFile.getInputStream());
            log.info("图片上传成功，filePath: {}", filePath);
        } catch (IOException e) {
            e.printStackTrace();
            log.info("---图片上传失败---");
        }

        // 线程中获取用户对象
        WmUser wmUser = WmTheadLocalUtil.getWmUser();

        // 封装返回数据
        WmMaterial wmMaterial = new WmMaterial();
        wmMaterial.setUrl(filePath);
        wmMaterial.setType(0);
        wmMaterial.setUserId(wmUser.getApUserId());
        wmMaterial.setIsCollection(0);
        wmMaterial.setCreatedTime(new Date());

        // 存入数据库
        this.save(wmMaterial);
        return ResponseResult.okResult(wmMaterial);
    }

    /**
     * 素材列表查询
     *
     * @param wmMaterialDto
     * @return
     */
    @Override
    public ResponseResult pictureList(WmMaterialDto wmMaterialDto) {
        log.info("---素材列表查询---");
        Integer page = wmMaterialDto.getPage();
        Integer size = wmMaterialDto.getSize();
        Short isCollection = wmMaterialDto.getIsCollection();

        // 校验page size
        if (page <= 0) {
            page = 1;
        }
        if (size <= 0) {
            size = 10;
        }

        LambdaQueryWrapper<WmMaterial> queryWrapper = new LambdaQueryWrapper<>();
        // 分页
        IPage page1 = new Page(page, size);
        // 是否收藏
        if (isCollection != null && isCollection == 1) {
            queryWrapper = Wrappers.<WmMaterial>lambdaQuery().eq(WmMaterial::getIsCollection, isCollection);
        }
        // 根据用户查询
        queryWrapper.eq(WmMaterial::getUserId, WmTheadLocalUtil.getWmUser().getApUserId());
        // 降序排序
        queryWrapper.orderByAsc(WmMaterial::getCreatedTime);
        IPage pageInfo = this.page(page1, queryWrapper);
        // 封装返回数据
        ResponseResult responseResult = new PageResponseResult(page, size, (int) pageInfo.getTotal());
        responseResult.setData(pageInfo.getRecords());
        return responseResult;
    }

    /**
     * 图片删除
     *
     * @param id
     * @return
     */
    @Override
    public ResponseResult delPicture(Integer id) {
        log.info("---图片删除---start");
        WmMaterial material = this.getById(id);
        // 根据id查询信息是否存在
        if (material == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.DATA_NOT_EXIST);
        }

        // 查询文件是否被引用
        WmNewsMaterial wmNewsMaterial = wmNewsMaterialMapper.selectById(id);
        if (wmNewsMaterial != null) {
            log.info("文件被引用，删除失败");
            return ResponseResult.errorResult(AppHttpCodeEnum.DELETE_PICTURE_ERROR);
        }
        // 删除文件
        boolean removeById = this.removeById(id);
        return removeById ? ResponseResult.okResult(AppHttpCodeEnum.SUCCESS) : ResponseResult.errorResult(AppHttpCodeEnum.DELETE_PICTURE_ERROR);
    }

    /**
     * 取消收藏 and 收藏
     *
     * @param id
     * @return
     */
    @Override
    public ResponseResult cancelCollectAndCollect(Integer id) {
        log.info("收藏与取消收藏");
        WmMaterial material = this.getById(id);
        // 根据id查询信息是否存在
        if (material == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.DATA_NOT_EXIST);
        }
        Integer isCollection = material.getIsCollection();
        boolean update = false;
        // 收藏
        if (isCollection == 0) {
            material.setIsCollection(1);
            LambdaQueryWrapper<WmMaterial> wrapper = Wrappers.<WmMaterial>lambdaQuery().eq(WmMaterial::getId, id);
            update = this.update(material, wrapper);
        }

        if (isCollection == 1) {
            // 取消收藏
            material.setIsCollection(0);
            LambdaQueryWrapper<WmMaterial> wrapper = Wrappers.<WmMaterial>lambdaQuery().eq(WmMaterial::getId, id);
            update = this.update(material, wrapper);
        }
        return update ? ResponseResult.okResult(AppHttpCodeEnum.SUCCESS) : ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
    }
}




